import storage from "@/uni_modules/uniapp-kantboot/libs/storage";
import config from "@/uni_modules/uniapp-kantboot/libs/config";
import request from "@/uni_modules/uniapp-kantboot/libs/request";
import rsa from "@/uni_modules/uniapp-kantboot/libs/rsa";


/**
 * 获取服务器的公钥
 */
let getServerPublicKey = () => {
    return storage.get(config.keyConfig.serverPublicKey);
}

/**
 * 设置服务器的公钥
 * @param serverPublicKey 服务器的公钥
 */
let setServerPublicKey = (serverPublicKey) => {
    storage.set(config.keyConfig.serverPublicKey, serverPublicKey);
}

let getClientKey = () => {
    return storage.get(config.keyConfig.clientKey);
}

/**
 * 清空key
 */
let clearKey = () => {
    storage.remove(config.keyConfig.clientKey);
    storage.remove(config.keyConfig.serverPublicKey);
}


let check = (obj) => {
    if (!obj.uri) {
        throw new Error("uri不能为空");
    }
    // 如果obj.uri前面有斜杠，去掉
    if (obj.uri.startsWith("/")) {
        obj.uri = obj.uri.substring(1);
    }

    if (!obj.data) {
        obj.data = {};
    }
    if (!obj.header) {
        obj.header = {};
    }
    if (!obj.isReconnect) {
        obj.isReconnect = false;
    }
    if (!obj.isReconnectState) {
        obj.isReconnectState = false
    }
    // 是否会跳转登录
    if (obj.isJumpLogin===null||obj.isJumpLogin===undefined) {
        obj.isJumpLogin = true;
    }
    return obj;
}


/**
 * 获取服务器的公钥
 */
let requestServerPublicKey = async (obj) => {
    let serverPublicKey = getServerPublicKey();
    if (!serverPublicKey) {
        return await new Promise((resolve,reject) => {
            // 向服务端请求公钥
            request.send({
                isReconnect: true,
                uri: "/security/request/getNewPublicKey",
                stateSuccess: (res) => {
                    // 保存服务端传来的公钥
                    setServerPublicKey(res.data);
                    resolve();
                },
                stateFail: (err) => {
                    // requestService.toStateFail(res, obj);
                    reject(err);
                }
            });
        });
    }
    return new Promise((resolve)=>{
        resolve();
    })

}

/**
 * 生成客户端的公钥
 * @returns {string}
 */
let generateClientKey = function () {
    let arr = [
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
        "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
        "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
    ];
    let clientKey = "";
    for (let i = 0; i < 32; i++) {
        clientKey += arr[Math.floor(Math.random() * arr.length)];
    }
    storage.set(config.keyConfig.clientKey, clientKey);
    return clientKey;
}

/**
 * 加密数据
 * @param options
 */
let encryptData = function (options) {
    // 获取服务端传来的公钥
    let serverPublicKey = storage.get(config.keyConfig.serverPublicKey);
    // 将options.data加密
    let encryptStr = rsa.encrypt(serverPublicKey, JSON.stringify(options.data));
    let clientKey = storage.get(config.keyConfig.clientKey);
    if (!clientKey) {
        clientKey = generateClientKey();
    }
    // 获取加密后的clientKey
    let clientKeyRsa = rsa.encrypt(serverPublicKey, clientKey);
    // 分为三个.分割，第一个是后端生成的公钥，第二个前端加密后的请求体，第三个是客户端生成的公钥
    return serverPublicKey + "." + encryptStr + "." + clientKeyRsa;
}




export default {
    check,
    getServerPublicKey,
    setServerPublicKey,
    clearKey,
    requestServerPublicKey,
    generateClientKey,
    encryptData,
    getClientKey
};